#include <asm-generic/errno-base.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
  key_t shm_key = ftok(".", 1);
  if (shm_key < 0) {
    perror("ftok fail");
    exit(-1);
  }

  int shm_id = shmget(shm_key, 1024, IPC_CREAT | IPC_EXCL | 0666);
  if (shm_id < 0) {
    if (errno == EEXIST) {
      shm_id = shmget(shm_key, 1024, 0666);
      if (shm_id < 0) {
        perror("shmget fail");
        exit(-1);
      }
    } else {

      perror("shmget fail");
      exit(-1);
    }
  }

  char* shm_buf = shmat(shm_id,NULL,0);
  if(shm_buf == (void*)-1)
  {
    perror("shmat fail");
    exit(-1);
  }

  while(1)
  {
    printf("%s\n",shm_buf);
    sleep(1);
  }

  shmdt(shm_buf);

  shmctl(shm_id,IPC_RMID,NULL);

  return 0;
}
